package com.wind.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wind.entity.*;
import com.wind.service.*;
import com.wind.vo.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/wind_user")
public class WindUserController {
    @Autowired
    private IUsersService usersService;

    @Autowired
    private ITestRecordService testRecordService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IExplainService explainService;

    @RequestMapping("/page")
    public Json page(@RequestBody String body) {
        JSONObject json = JSON.parseObject(body);
        String nick = json.getString("nickname");
        int current = json.getIntValue("current");
        int size = json.getIntValue("size");
        if (current == 0) current = 1;
        if (size == 0) size = 10;
        Wrapper<Users> wrapper = new EntityWrapper<>();
        wrapper.like("nickname", nick);
        wrapper.orderBy("createTime", false);
        Page<Users> page = usersService.selectPage(new Page<>(current, size), wrapper);
        page.getRecords().stream().forEach(obj->{
            obj.setTestCount(Optional.ofNullable(testRecordService.selectCount(new EntityWrapper<TestRecord>()
                    .eq("user_id",obj.getEmail()))).orElse(0));
            obj.setCounselCount(Optional.ofNullable(orderService.selectCount(new EntityWrapper<Order>()
            .eq("user_id",obj.getId()))).orElse(0));
            obj.setResultCount(Optional.ofNullable(0).orElse(0));
        });
        return Json.succ().data("page", page);
    }

    @RequestMapping("/disEnable")
    public Json disEnable(@RequestBody String body) {
        JSONObject json = JSON.parseObject(body);
        Integer id = json.getIntValue("id");
        Integer isActive = json.getIntValue("isActive");
        Users users = usersService.selectById(id);
        if (users == null) {
            return Json.fail("获取用户信息失败");
        }
        users.setIsActive(isActive);
        if(!usersService.updateById(users)){
            return Json.fail("操作失败");
        }
        return Json.succ("操作成功");
    }
}
